import React, { Component, useCallback, useEffect } from 'react';
import 'antd/dist/antd.css';
import styles from '../style.less';
import { Row, Col,List,Menu,notification,Checkbox,Typography} from 'antd';
import grid1Img from '@/assets/camera/grid-1.png';
import grid4Img from '@/assets/camera/grid-4.png';
import grid9Img from '@/assets/camera/grid-9.png';
import guanbi from '@/assets/camera/guanbi.png';
import huikan from '@/assets/camera/huikan.png';
import CameraPlayer from '../../components/CameraPlayer'
import { connect,history } from 'umi';
const { Paragraph } = Typography;
const { SubMenu } = Menu;

@connect(({ cameraLive, loading }) => ({
  cameraLive,
  loading: loading.models.cameraLive,
}))
class CameraGrid extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: 'userId',// 用户id 缺省值
      collapsed: false,
      mode: 'inline',
      showNumber: 9,
      selectPlayer: 0,
      data: [{},{},{},{},{},{},{},{},{}],
    };
    const {
      loading,
      dispatch,
      cameraLive: { channelList },
    } = props;
    this.menuSelectKeys = [];
    this.handleChangeNumber = this.handleChangeNumber.bind(this);
    this.messageOnChange = this.messageOnChange.bind(this);
    this.videoClose = this.videoClose.bind(this);
    this.handleGotoHistory = this.handleGotoHistory.bind(this);
  }
  componentDidMount() {
    const userData = localStorage.getItem("antd-pro-authority")
    let {userId} = this.state;
    if(userData){
      const  userInfo = JSON.parse(userData);
      if(userInfo){
        userId = userInfo.userId;
        this.setState({
          userId
        })
      }
    }
    this.handleQueryChannel();

    const showMessage =localStorage.getItem(`cameraShowMessage_${userId}`);
    if(showMessage===undefined || showMessage===null || showMessage==='false'){
      notification.info({
        duration:null,
        message: '使用方法',
        description: <Paragraph>
          <ol>
            <li>点击选择视频窗口
            </li>
            <li>点击选择摄像头，等待对应摄像头画面显示在选定的窗口内
            </li>
          </ol>
        </Paragraph>,
        key: 'cameraShowMessage',
        btn:<Checkbox onChange={this.messageOnChange.bind(this)}>不再提示</Checkbox>
      })
    }
  }

  messageClose(){
    notification.destroy('cameraShowMessage');
  }

  messageOnChange(e) {
    const {userId} = this.state;
    localStorage.setItem(`cameraShowMessage_${userId}`,e.target.checked)
  }

  componentWillUnmount() {
    notification.destroy('cameraShowMessage');
  }

  messageInfo = () => (
    <div className={styles.messageContent}>
      <div className={styles.messageHeader}>
        <span>使用方法</span>
        <img src={guanbi} onClick={this.messageClose}/>
      </div>
      <div>
        1、点击选择视频窗口<br/>
        2、点击选择摄像头，等待对应摄像头画面县十四在选定的窗口内
      </div>
      <Checkbox onChange={this.messageOnChange}>下次不在提示</Checkbox>
    </div>
  );

  componentDidUpdate(prevProps){
    if(prevProps.cameraLive.channelList !== this.props.cameraLive.channelList){
      this.getLocationGridData();
    }
  }

  getLocationGridData(){
    const {userId,data} = this.state;
    const gridJson = localStorage.getItem(`cameragrid_${userId}`);
    if(gridJson){
      const gridData = JSON.parse(gridJson);
      if(gridData){
        // 保持的有历史数据
        const {cameraLive: {channelList} } = this.props;
        for (let i=0;i<gridData.length;i++){
          const item = gridData[i];
          const channelItem = channelList.find((channel)=>{
            return item === channel.channelId;
          })
          if(channelItem){
            data[i] = channelItem;
          }
        }
        this.setState({
          data
        })
      }
    }
  }

  saveLocationGridData(){
    const {userId,data} = this.state;
    const gridData = ['0','0','0','0','0','0','0','0','0'];
    for (let i=0;i<data.length;i++) {
      const item = data[i];
      if(item.channelId){
        gridData[i] = item.channelId;
      }
    }
    localStorage.setItem(`cameragrid_${userId}`,JSON.stringify(gridData))
  }

  handleQueryChannel(){
    const { dispatch } = this.props;
    dispatch({
      type: 'cameraLive/fetch',
      payload: {},
    })
  }

  handleChangeNumber(number) {
    this.setState({
      showNumber: number,
      selectPlayer: 0,
    })
  };

  handleSelectPlayer(index){
    this.menuSelectKeys = [''];
    this.setState({
      selectPlayer: index,
    })
  }

  handleSelectCamera(data){
    this.menuSelectKeys = [data.channelId];
    const oldData = this.state.data;
    oldData[this.state.selectPlayer] = data;
    this.setState({
      data: oldData,
    })
    // 保持选择的数据
    this.saveLocationGridData();
  }

  videoClose(event,index){
    const  e = event || window.event;
    if(e.stopPropagation){
      e.stopPropagation();
    }else {
      e.cancelBubble = true;
    }
  }

  getNowFormatDate() {
    const date = new Date();
    const seperator1 = "-";
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    const currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  }

  handleGotoHistory(event,index){
    const  e = event || window.event;
    if(e.stopPropagation){
      e.stopPropagation();
    }else {
      e.cancelBubble = true;
    }
    const {data} = this.state;
    const item = data[index];
    if(item.channelId){
      history.push({
        pathname: '/camera/replay',
        query: {
          channelId: item.channelId,
          date: this.getNowFormatDate(),
        },
      });
    }
  }

  render() {
    const gridItem = [];
    const {showNumber,data} = this.state;
    if(showNumber ===1) {
      gridItem.push(
        <div className={`${styles.item} ${styles.grid_1}`} onClick={(event) =>this.handleSelectPlayer(0)}>
          <CameraPlayer liveData={data[0]}/>
          {
            data[0].channelId ?<img className={styles.videoClose} title="回看录像" src={huikan} onClick={(event) =>this.handleGotoHistory(event,0)}/>:''
          }
        </div>,
      )
    }else if(showNumber >4){
      for (let i = 0; i < showNumber; i++) {
        gridItem.push(
          // {`${styles.item} ${styles.grid_9}`}
          <div className={`${styles.item} ${styles.grid_9} ${i===this.state.selectPlayer?styles.active:""}`} onClick={(event) =>this.handleSelectPlayer(i)}>
            <CameraPlayer liveData={data[i]}/>
            {
              data[i].channelId?<img className={styles.videoClose} title="回看录像" src={huikan} onClick={(event) =>this.handleGotoHistory(event,i)}/>:''
            }
          </div>,
        )
      }
    }else if(showNumber >1){
      for (let i = 0; i < showNumber; i++) {
        gridItem.push(
          <div className={`${styles.item} ${styles.grid_4}`} onClick={(event) =>this.handleSelectPlayer(i)}>
            <CameraPlayer liveData={data[i]}/>
            {
              data[i].channelId?<img className={styles.videoClose} title="回看录像" src={huikan} onClick={(event) =>this.handleGotoHistory(event,i)}/>:''
            }
          </div>,
        )
      }
    }
    const {cameraLive: {channelList} } = this.props;
    return (
      <div className={styles.camera} >
        <div className={styles.cameraList}>
          <span className={styles.cameraListTitle}>选择摄像头</span>
          <Menu selectedKeys={this.menuSelectKeys} mode="inline">
            {
              channelList.map((item, index) => {
                return <Menu.Item className={styles.camera_menu} key={item.channelId} onClick={() => { this.handleSelectCamera(item) }}>{item.name}</Menu.Item>
              })
            }
          </Menu>
        </div>
        <div className={styles.cameraGirdLayout}>
          <div className={styles.cameraGirdTitle}>
            <div className={styles.cameraGirdTitleRight}>
              <img onClick={(event) =>this.handleChangeNumber(1)} className={styles.cameraGirdImg} src={grid1Img} alt="1路视频" />
              <img onClick={(event) =>this.handleChangeNumber(4)} className={styles.cameraGirdImg} src={grid4Img} alt="4路视频" />
              <img onClick={(event) =>this.handleChangeNumber(9)} className={styles.cameraGirdImg} src={grid9Img} alt="9路视频"  />
            </div>
            <div className={styles.cameraGird}>
              {gridItem}
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default CameraGrid;
